package com.course.oauth2.config;

import com.course.common.response.BaseResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @PROJECT_NAME: course
 * @DESCRIPTION: 认证失败处理
 * @Author: 涂玄武
 * @DATE: 2021/6/22 10:10
 */
@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Resource
    private ObjectMapper objectMapper;

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        //返回JSON
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        //状态码 401
        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        //写出
        PrintWriter out = httpServletResponse.getWriter();
        String errorMessage = e.getMessage();
        if (StringUtils.isBlank(errorMessage)){
            errorMessage = "登录失效!";
        }
        BaseResponse result = new BaseResponse().failure(errorMessage);
        out.write(objectMapper.writeValueAsString(result));
        out.flush();
        out.close();
    }
}
